package com.windoent.yugioh.ui.fragment.saishi.baoming;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.AuthXuanShouAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.AuthPlayerData;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.SearchView;
import com.windoent.yugioh.widget.dialog.ExitGameReasonDialog;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/6/8 15:32
 * desc   :审核选手
 */
public class BaoMingAuthXuanShouFragment extends BaseFragment {
    private SearchView mSearch;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private AuthXuanShouAdapter adapter;
    private String text = "";
    private Button mBtnGetCode;
    private int status;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_baoming_auth_xuanshou;
    }

    public static BaoMingAuthXuanShouFragment newsInstance(String id, String response) {
        //创建 Bundle
        BaoMingAuthXuanShouFragment fragment = new BaoMingAuthXuanShouFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        lBundle.putString("response", response);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initData() {
        initAdapter();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事报名中审核选手tab");
        }
        getDetailsId();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事报名中审核选手tab");
        }
    }

    private String id = "";

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            String response = bundle.getString("response");
            initRefreshData(text);
            fresh(text);
        }
    }

    private void initListener() {
        mSearch.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    text = mSearch.getEditStr();
                    initRefreshData(text);
                    fresh(text);
                    return true;
                }
                return false;
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (status == 2) {
                    dianjiaStartGame(id);
                } else if (status == 1) {
                    ToastUtils.showText(getString(R.string.string_nt_immediately_start));
                } else {
                    ToastUtils.showText(getString(R.string.string_already_start));
                }
            }
        });
    }

    private void initView() {
        mSearch = (SearchView) mView.findViewById(R.id.search);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mBtnGetCode = (Button) mView.findViewById(R.id.btn_get_code);
    }

    private void initRefreshData(String text) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(text);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(text);
            }
        });
    }

    private void loadMore(String text) {
        mCount = mCount + 1;
        getAuthXuanShouListData(text, mCount + "", limit, false);
    }

    //店家开启比赛
    private void dianjiaStartGame(String id) {
        showLoadingDialog("");
        PhoneLive.dianjiaStartGame(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        if (fromJson.getCode() == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(fromJson.getMsg(), getString(R.string.string_start_game_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    status = 3;
                                    mBtnGetCode.setSelected(true);
                                    mBtnGetCode.setText(getString(R.string.string_already_start));
                                    fresh(id);
                                }
                            });
                        } else {
                            String msg = fromJson.getMsg();
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_start_game_fail), msg);
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void fresh(String text) {
        getGameStatusRole(id, text);
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id, String text) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid != 2 && statusid != 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid == 2) {
                                        mCount = 1;
                                        getAuthXuanShouListData(text, mCount + "", limit, true);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new AuthXuanShouAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<AuthPlayerData.DataBean.ResBean> data = adapter.getData();
                AuthPlayerData.DataBean.ResBean playerBean = data.get(position);
                if (playerBean != null) {
                    int uid = playerBean.getUid();
                    showExitGameDialog(uid + "");
                }
            }
        });
    }

    //退赛理由
    private void showExitGameDialog(String userId) {
        ExitGameReasonDialog dialog = new ExitGameReasonDialog(mContext);
        dialog.setOnclickListener(new ExitGameReasonDialog.onClickListener() {
            @Override
            public void onClick(String string) {
                dianjiaExitPlayer(userId, string);
            }
        });
        dialog.show();
    }

    //商家退出选手
    private void dianjiaExitPlayer(String userId, String remark) {
        showLoadingDialog("");
        PhoneLive.dianjiaExitPlayer(getUserToken(), id, userId, remark, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_exit_judge_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    fresh(text);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_exit_judge_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    //列表
    private void getAuthXuanShouListData(String title, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getAuthPlayersList(getUserToken(), id, title, page, limit, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            AuthPlayerData json = gson.fromJson(response, AuthPlayerData.class);
                            if (json != null) {
                                AuthPlayerData.DataBean data = json.getData();
                                if (data != null) {
                                    status = data.getStatus();
                                    if (status != 2) {
                                        mBtnGetCode.setSelected(true);
                                        if (status == 1)
                                            mBtnGetCode.setText(getString(R.string.string_nt_immediately_start));
                                        else
                                            mBtnGetCode.setText(getString(R.string.string_already_start));
                                    } else {
                                        mBtnGetCode.setSelected(false);
                                        mBtnGetCode.setText(getString(R.string.string_start_games));
                                    }
                                    List<AuthPlayerData.DataBean.ResBean> res = data.getRes();
                                    if (res != null) {
                                        if (fresh) {
                                            mSmartLayout.finishRefresh(true);
                                            adapter.setNewInstance(res);
                                        } else {
                                            mSmartLayout.finishLoadMore(true);
                                            adapter.addData(res);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
